<template>
  <div class="image-viewer" @wheel="handleWheel" @mousedown="startDrag" @mousemove="drag" @mouseup="stopDrag">
    <img v-if="file" :src="file" :style="{ transform: `translate(${dragX}px, ${dragY}px) scale(${zoom})`, objectFit: 'contain' }" />
  </div>
</template>

<script setup>
import {ref, watch} from 'vue';

const props = defineProps({
  file: String, // 修改为接收字符串
});

const file = ref(props.file);
const zoom = ref(1.0);
const dragX = ref(0);
const dragY = ref(0);
let isDragging = false;

watch(() => props.file, (newFile) => {
  file.value = newFile;
  zoom.value = 1.0; // 重置缩放比例
  dragX.value = 0; // 重置拖拽位置
  dragY.value = 0;
}, {immediate: true});

const handleWheel = (event) => {
  event.preventDefault();
  const rect = event.currentTarget.getBoundingClientRect();
  const centerX = event.clientX - rect.left;
  const centerY = event.clientY - rect.top;

  const oldZoom = zoom.value;
  if (event.deltaY < 0) {
    // 向上滚动，放大图片
    zoom.value += 0.1;
  } else {
    // 向下滚动，缩小图片
    zoom.value -= 0.1;
    if (zoom.value < 1.0) {
      zoom.value = 1.0; // 最小缩放比例
    }
  }

  const scaleDelta = zoom.value / oldZoom;
  dragX.value += (centerX - dragX.value) * (1 - scaleDelta);
  dragY.value += (centerY - dragY.value) * (1 - scaleDelta);
};

const startDrag = (event) => {
  event.preventDefault(); // 阻止默认的拖拽行为
  isDragging = true;
  document.body.style.userSelect = 'none'; // 防止文本被选中
};

const drag = (event) => {
  if (isDragging) {
    dragX.value += event.movementX;
    dragY.value += event.movementY;
  }
};

const stopDrag = () => {
  isDragging = false;
  document.body.style.userSelect = ''; // 恢复文本选中
};
</script>

<style scoped>
.image-viewer {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.image-viewer img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  transition: transform 0.3s ease;
  user-select: none;
}
</style>
